<template>
  <div id="doMyself-components-box" v-loading.fullscreen.lock="fullscreenLoading" >


    <!-- <div class="top-state">
      <div class="productRegister">
       <h2>公众号设置</h2>
       <div class="flex">
        <div class="flex-1">
          <div class="upfile-title fs14 mar-top-5 border-btm  pad-bottom-10">上传公众号二维码
            <el-tooltip
              trigger="hover"
            >
              <div slot="content" style="width: 420px">
                <p>上传公众号二维码图片，客户产品注册过程中可关注公众号</p>
              </div>
              <i class="el-icon-question" />
            </el-tooltip>
          </div>
        </div>
        <div>
          <el-switch
            v-model="productSearchOnMobile"
            @change="saveFunc($event, 'productSearchOnMobile')"
          ></el-switch>
          {{ productSearchOnMobile ? "启用" : "禁用" }}
        </div>
       </div>
      <div v-show="isUploadFile">
        
        <div class="uploadPictures flex-1">
          <upFile v-if="isUploadFile" @productMg="getImgUrl" @removePic="removePic" :uploadText="uploadText"  :imgUrl="imgUrl"></upFile>
        </div>
        <div class="uploadTips">
              <p class="tips">1.图片格式PNG, JPG/JPEG, BMP</p>
              <p class="tips">2.建议上传尺寸比例为1:1</p>
              <p class="tips">3.大小不超过200M</p>
        </div>
        </div>
      </div>
    </div> -->
    <div class="top-state mt15" v-if="haveWx===0">
      <div>
        <h2>{{$t('portal.wxSet.title1')}}</h2>
        <p>{{$t('setting.messageChannel.tip.noBindWxTip')}}</p>
        <div class="wx-img">
          <img :src="wxDefaultImage" alt />
        </div>
        <button type="submit" class="btn btn-primary" @click="concatWx">{{$t('portal.wxSet.title1')}}</button>
      </div>
    </div>

    <div v-else-if="haveWx===1">
      <div class="top-menu" v-if="!openMessageReform">
        <nav :class="topType===0?'nav-checked':''" @click="topType=0">{{$t('portal.wxSet.title1')}}</nav>
        <nav :class="topType===1?'nav-checked':''" @click="topType=1">{{$t('portal.wxSet.linkText1')}}</nav>
      </div>

      <div class="menu-set-box" v-if="topType===0">
        <div class="top-state">
          <div>
            <h2>{{$t('portal.wxSet.title1')}}</h2>
            <div class="wx-con">
              <div class="wx-img">
                <img
                  v-show="wxInfo.headImg === null"
                  :src="wxDefaultImage"
                  alt
                />
                <img v-show="wxInfo.headImg !== null" :src="wxInfo.headImg" alt />
              </div>
              <div>
                <p>{{$t('setting.messageChannel.nickname')}}：{{wxInfo.nickName}}</p>
                <p>{{$t('setting.messageChannel.principalName')}}：{{wxInfo.principalName}}</p>
              </div>
            </div>
            <el-button type="plain-third" class="btn btn-ghost cancel-wx" @click="desertWx">{{$t('portal.wxSet.btn1')}}</el-button>
          </div>
        </div>
        <div class="top-state">
          <menu-set @pageLoading="pageLoading" :menu-arr="menuArr" @changeMenuArr="changeMenuArr"></menu-set>
        </div>

        <div class="top-state" v-if="openMessageReform">
          <div class="set-arr-item">
            <div class="set-arr-item-left">
              <div class="item">
                <span>{{$t('portal.wxSet.linkText2')}}</span>
              </div>
              <p>{{$t('portal.wxSet.text2')}}</p>
            </div>
            <div class="flex-1"></div>
            <div class="set-arr-item-right">
              <div class="flex-1"></div>
              <el-switch
                v-model="totalActive"
                :active-color="getThemeColor"
                inactive-color="#e0e1e2"
                :active-text="totalActive?$t('common.base.open'):$t('common.base.close')"
                :active-value="true"
                :inactive-value="false"
                @change="mainChange"
              ></el-switch>
            </div>
          </div>
        </div>
      </div>
      <div v-if="topType==1">
        <div class="top-state">
          <!-- {{$t('portal.wxSet.title8')}} start -->
          <div>
            <h2>{{$t('portal.wxSet.title8')}}</h2>
            <div :class="totalActive===true?'mar-b-10 set-arr-item':'set-arr-item'">
              <div class="set-arr-item-left">
                <!-- <el-tooltip class="item" effect="dark" content="{{$t('portal.wxSet.linkText2')}}" placement="bottom"> -->
                <div class="item">
                  <span>{{$t('portal.wxSet.linkText2')}}</span>
                </div>
                <!-- </el-tooltip> -->
                <p>{{$t('portal.wxSet.text2')}}</p>
              </div>
              <div class="flex-1"></div>
              <div class="set-arr-item-right">
                <div class="flex-1"></div>
                <el-switch
                  v-model="totalActive"
                  :active-color="getThemeColor"
                  inactive-color="#e0e1e2"
                  :active-text="totalActive?$t('common.base.open'):$t('common.base.close')"
                  :active-value="true"
                  :inactive-value="false"
                  @change="mainChange"
                ></el-switch>
              </div>
            </div>

            <div class="set-arr-box" v-show="totalActive===true">
              <div class="set-arr-item" v-for="(item,index) in toastSetArr" :key="index">
                <div class="set-arr-item-left">
                  <div class="item">
                    <!-- <el-tooltip class="item" effect="dark" :content="{{item.title}}" placement="bottom"> -->
                    <span>{{item.title}}</span>
                    <!-- <i class="iconfont icon-info mar-l-10"></i> -->

                    <!-- </el-tooltip> -->
                  </div>
                  <p v-if="item.time===null">{{item.childTitle}}</p>
                  <div class="small-form" v-else>
                    {{$t('portal.wxSet.text3')}}
                    <el-input
                      :disabled="item.radius?false:true"
                      v-model="item.time"
                      style="padding:none;display: inline;"
                      @input="inputTime"
                      type="number"
                    />{{$t('portal.wxSet.text4')}}
                  </div>
                </div>
                <div class="flex-1"></div>
                <set-arr-item-right
                  :disabled="item.radius>0?false:true"
                  :item-data="item"
                  :item-index="index"
                  @pageLoading="pageLoading"
                ></set-arr-item-right>
              </div>
            </div>
          </div>
          <!-- 通知设置 end -->
          <toast-template v-if="totalActive===true" @pageLoading="pageLoading"></toast-template>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import menuSet from './components/menuSet';
import upFile from './components/upFile';
import toastTemplate from './components/toastTemplate';
import setArrItemRight from './components/setArrItemRight';
import {
  getAuthInfoWX,
  saveWxMessage,
  eventTypeList,
  taskTypeList,
  saveSendTime,
  cancleAuthorizer,
  wechatQrCodeImageSwitch,
  uploadWechatQrCodeImage,
  getWechatQrCodeImageConfig
} from '@src/api/DoMyself.js';
import { Message } from 'element-ui';
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts';
import { isDisplay } from '@src/api/ProductV2Api';

/* util */
import { getRootWindowInitData } from '@src/util/window'
const rootWindowInitData = getRootWindowInitData()

let timeOut;
let inputTimeOut;
import { getOssUrl } from '@src/util/assets'
const wxDefaultImage = getOssUrl('/wx/wxDefault.png')
export default {
  name: 'wx-set',
  mixins: [ThemeMixin],
  watch: {
    topType: {
      handler(newValue, oldValue) {},
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      wxDefaultImage,
      imgUrl:'',
      uploadText:this.$t('common.base.clickForUploading'),
      pic_url:'',
      isUploadFile:false,
      productSearchOnMobile:false,
      topType: 0, // 微信设置顶部切换 0 绑定公众号 1 公众号通知
      haveWx: -1,
      concatWxUrl: '', // 授权微信公众号的链接
      totalActive: false,
      fullscreenLoading: false, // 整屏loading
      wxInfo: {},
      openMessageReform:rootWindowInitData.openMessageReform, //是否灰度
      toastSetArr: [ 
        {
          title: this.$t('common.notification.eventApportionNotice'),
          childTitle: this.$t('portal.wxSet.subTitle1'),
          options: [],
          select: [],
          pleasHolder: this.$t('portal.wxSet.text1'),
          radius: false,
          time: null,
          radiusKey:'smsEventAllot',
          selectKey:'eventAllotEventTypeList'
        },
        {
          title: this.$t('common.notification.eventFinishNotice'),
          childTitle: this.$t('portal.wxSet.subTitle2'),
          options: [],
          select: [],
          pleasHolder: this.$t('portal.wxSet.text1'),
          radius: false,
          time: null,
          radiusKey:'smsEventFinish',
          selectKey:'eventFinishEventTypeList'
        },
        {
          title: this.$t('portal.wxSet.title2'),
          childTitle: this.$t('portal.wxSet.subTitle3'),
          options: [],
          select: [],
          pleasHolder: this.$t('task.components.allotRuleModal.allTaskType'),
          radius: false,
          time: null,
          radiusKey:'smsTaskResponse',
          selectKey:'taskResponseTaskTypeList'
        },
        {
          title: this.$t('portal.wxSet.title3'),
          childTitle: this.$t('portal.wxSet.subTitle4'),
          options: [],
          select: [],
          pleasHolder: this.$t('task.components.allotRuleModal.allTaskType'),
          radius: false,
          time: null,
          radiusKey:'smsTaskStart',
          selectKey:'taskStartTaskTypeIdList'
        },
        {
          title: this.$t('portal.wxSet.title4'),
          childTitle: this.$t('portal.wxSet.subTitle5'),
          options: [],
          select: [],
          pleasHolder: this.$t('task.components.allotRuleModal.allTaskType'),
          radius: false,
          time: null,
          radiusKey:'smsTaskFinish',
          selectKey:'taskFinishTaskTypeList'
        },
        {
          title: this.$t('portal.wxSet.title5'),
          options: [],
          select: [],
          pleasHolder: this.$t('task.components.allotRuleModal.allTaskType'),
          radius: false,
          time: '',
          radiusKey:'taskPlanTimeRemind',
          selectKey:'taskPlanTimeTaskTypeList'
        },
        {
          title: this.$t('portal.wxSet.title6'),
          childTitle: this.$t('portal.wxSet.subTitle6'),
          options: [],
          select: [],
          pleasHolder: this.$t('task.components.allotRuleModal.allTaskType'),
          radius: false,
          time: null,
          radiusKey:'smsModifyPlanTime',
          selectKey:'modifyTaskPlanTimeTaskTypeIdList'
        },
      ],
      eventArr: [],
      taskArr: [],
      timeInputing: 0,
      scanQrCode: false,
      menuArr: []
    };
  },
  computed: {},
  created() {
    sessionStorage.removeItem('wx_auth_auth_page_close');
    this.getWxInfo();
  },
  mounted(){
    // this.productSearchOnMobile = sessionStorage.getItem('switchButton') === 'true' ? true : false
    // this.isUploadFile = this.productSearchOnMobile
    // this.getWechatQrCode() 
  },
  methods: {
    goBack() {
  
      // // 工单新建
      //  if (this.isTaskCreate) {
      //   let id = window.frameElement.dataset.id;
        
      //   return this.$platform.closeTab(id)
      // }
      
      parent.frameHistoryBack(window)
      
    },
    // 获取图片地址
    // getImgUrl(item){
    //    uploadWechatQrCodeImage({item}).then(res=>{
    //           if(res.status == 0){
    //             this.getWechatQrCode() 
    //           }
    //         })
          
    // },
    // removePic() {
    //   uploadWechatQrCodeImage().then(res=>{
    //     if(res.status == 0){
    //       this.getWechatQrCode() 
    //     }
    //   })
    // },
    // 获取公众号二维码配置
    // getWechatQrCode(){
    //    getWechatQrCodeImageConfig().then(res=>{
    //     if(res.status == 0){
    //       this.imgUrl = res.data.wechatQrCodeImage?.item?.url || ''
    //       this.isUploadFile = this.productSearchOnMobile = res.data.wechatQrCodeImageSwitch
    //     }
    //   })
    // },
    // 开启关闭
    // saveFunc(e){
    //   isDisplay().then(r=>{
    //     if(r.status == 0){
    //       this.productSearchOnMobile = e
    //       // sessionStorage.setItem('switchButton',this.productSearchOnMobile)
    //       wechatQrCodeImageSwitch({qrcodeImageSwitch:this.productSearchOnMobile}).then(res=>{
    //         if(res.status == 0){
    //           this.isUploadFile = this.productSearchOnMobile
    //         }
    //       })
    //     }else{
    //       this.$message.warning('请前往系统管理打开产品注册管理设置按钮');
    //     }
    //   })
    // },
    pageLoading(data = false) {
      if (this.fullscreenLoading === data) return;
      this.fullscreenLoading = data;
    },
    getWxInfo() {
      if (sessionStorage.getItem('wx_auth_auth_page_close') === 'true') {
        this.scanQrCode = false;
        sessionStorage.removeItem('wx_auth_auth_page_close');
        return;
      }
      if (!this.scanQrCode) {
        // 如果是轮询不需要loading 加载动画
        this.pageLoading(true);
      }

      getAuthInfoWX()
        .then(res => {
          if (res.data.status === 0) {
            // 未绑定公众号
            this.haveWx = 0;
            this.concatWxUrl = res.data.mpAuthorizeUrl;
            if (this.scanQrCode === true) {
              timeOut = setTimeout(() => {
                this.getWxInfo();
              }, 2500);
            }
            return;
          } else if (res.data.status === 2) {
            clearTimeout(timeOut);
            // 未绑定公众号
            this.haveWx = 0;
            this.scanQrCode = false;
            // 这是哪个页面来着
            this.$platform.closeTab('wx_auth');
            this.$platform.alert(res.data.message || this.$t('common.base.tip.systemIsError'));
            return;
          } else if (res.data.status === 3) {
            clearTimeout(timeOut);
            // 未绑定公众号
            this.haveWx = 0;
            this.scanQrCode = false;
            this.$platform.closeTab('wx_auth');
            this.$platform.alert(res.data.message || this.$t('common.base.tip.systemIsError'));
            return;
          }
          this.haveWx = 1;
          if (this.scanQrCode) {
            this.$platform.closeTab('wx_auth');
          }
          this.scanQrCode = false;
          this.wxInfo = res.data.data;
          this.menuArr = res.data.data.wechatMenu
            ? JSON.parse(res.data.data.wechatMenu).menu.button
            : [];
          if (res.data.eventTypeList) {
            let arr = res.data.eventTypeList.map(res => {
              return { label: res.name, value: res.id };
            });
            // this.toastSetArr[0].options = arr;
            this.toastSetArr.find(v=>v.radiusKey == 'smsEventAllot').options = arr
            // this.toastSetArr[1].options = arr;
            this.toastSetArr.find(v=>v.radiusKey == 'smsEventFinish').options = arr
          }
          if (res.data.taskTypeList) {
            let arr = res.data.taskTypeList.map(res => {
              return { label: res.name, value: res.id };
            });
            // this.toastSetArr[2].options = arr;
            this.toastSetArr.find(v=>v.radiusKey == 'smsTaskResponse').options = arr

            // this.toastSetArr[3].options = arr;
            this.toastSetArr.find(v=>v.radiusKey == 'smsTaskFinish').options = arr

            // this.toastSetArr[4].options = arr;
            this.toastSetArr.find(v=>v.radiusKey == 'taskPlanTimeRemind').options = arr

            this.toastSetArr.find(v=>v.radiusKey == 'smsTaskStart').options = arr

            this.toastSetArr.find(v=>v.radiusKey == 'smsModifyPlanTime').options = arr


          }
          if (res.data.wxTemplateMessageConfig) {
            let wxToast = res.data.wxTemplateMessageConfig;
            this.totalActive = wxToast.wxRemindMaster;
            // for (let i = 0; i < this.toastSetArr.length; i++) {
            //   this.toastSetArr[i].radius = wxToast[setRaduisArr[i]];
            //   if (wxToast[setSelectArr[i]].length > 0) {
            //     this.toastSetArr[i].select = wxToast[setSelectArr[i]];
            //   }
            //   if (i === 4 && wxToast.reportSendTime) {
            //     this.toastSetArr[i].time = wxToast.reportSendTime;
            //   }
            // }
            this.toastSetArr.map((v)=>{
              const radiusKey = v.radiusKey
              const selectKey = v.selectKey
              v.radius = wxToast[radiusKey]
              v.select = wxToast[selectKey]
              if(radiusKey === 'taskPlanTimeRemind' && wxToast.reportSendTime){
                v.time = wxToast.reportSendTime
              }
            })
          }
        })
        .catch(err => {
          console.log(err, 'erro');
        })
        .finally(res => {
          this.pageLoading(false);
        });
    },
    async mainChange(e) {
      this.totalActive = !e;
      if (e === true) {
        if (this.wxInfo.serviceTypeInfo != 2) {
          return this.$platform.alert(
            this.$t('portal.wxSet.text6')
          );
        }
        const res_plat = await this.$platform.confirm(
          this.$t('portal.wxSet.text7')
        );
        if (!res_plat) return;
      }
      this.pageLoading(true);
      saveWxMessage({
        message: 'wxRemindMaster',
        state: e
      })
        .then(res => {
          if (res.succ) {
            this.totalActive = e;
            if(e){
              // 开启开关重新获取授权数据
              this.getWxInfo()
            }
          }
          this.pageLoading(false);
          
        })
        .catch(err => {});
    },

    inputTime(e) {
      clearTimeout(inputTimeOut);
      inputTimeOut = setTimeout(() => {
        if (!/^(([0-9]+)|([0-9]+\.[0-9]{0,2}))$/.test(e)) {
          this.$platform.alert(this.$t('portal.wxSet.text5'));
          // this.toastSetArr[4].time = '';
          this.toastSetArr.find(v=>v.radiusKey == 'taskPlanTimeRemind').time = ''
          return;
        }
        saveSendTime({
          // reportSendTime: this.toastSetArr[4].time
          reportSendTime:this.toastSetArr.find(v=>v.radiusKey == 'taskPlanTimeRemind').time
        }).then(res => {});
      }, 1500);
    },
    concatWx() {
      if (this.scanQrCode) {
        return;
      }
      this.scanQrCode = true;
      let fromId = window.frameElement.getAttribute('id');
      this.$platform.openTab({
        id: 'wx_auth',
        title: this.$t('portal.wxSet.title7'),
        url: this.concatWxUrl,
        reload: true,
        close: true,
        fromId,
        isNeedConvertUrl: false
      });
      // this.$platform.openLink(this.concatWxUrl);
      this.getWxInfo();
    },
    async desertWx() {
      try {
        const res_ = await this.$platform.confirm(
          this.$t('portal.wxSet.confirmTip1', {nickName: this.wxInfo.nickName})
        );
        if (!res_) return;
        cancleAuthorizer()
          .then(res => {
            this.pageLoading(false);
            this.getWxInfo();
            Message.success({
              message: this.$t('portal.wxSet.tipText1'),
              type: 'success'
            });
          })
          .catch(err => {
            this.$platform.alert(err);
          });

        // this.$eventBus.$emit("customer_info_record.update_record_list");
      } catch (e) {
        console.error(e, 'err');
      }
    },
    openTab(url) {
      window.location.href = url;
    },
    changeMenuArr(e) {
      this.menuArr = e;
    }
  },
  beforeDestroy() {
    clearTimeout(timeOut);
  },
  components: {
    [menuSet.name]: menuSet,
    upFile,
    [toastTemplate.name]: toastTemplate,
    [setArrItemRight.name]: setArrItemRight
  }
};
</script>
<style lang="scss">
p {
  font-size: 16px;
  margin: 0;
  padding: 0;
}
.mar-b-10 {
  margin-bottom: 10px;
}
.mar-l-10 {
  margin-left: 10px;
}
.mar-r-15 {
  margin-right: 15px;
}
.color-g {
  color: #55b7b4;
}
.top-menu {
  background: #fff;
  box-sizing: border-box;
  padding: 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  nav {
    width: 194px;
    height: 35px;
    text-align: center;
    line-height: 35px;
    font-size: 12px;
    border: 1px solid #d2d6de;
    overflow: hidden;
    position: relative;
    cursor: pointer;
  }
  nav:nth-child(1) {
    border-right: none;
    border-top-left-radius: 2px;
    border-bottom-left-radius: 2px;
  }
  nav:last-child {
    border-top-right-radius: 2px;
    border-bottom-right-radius: 2px;
  }
  .nav-checked {
    @include backgroundColor();
    @include borderColor();
    color: #fff;
  }
}

.menu-set-box {
  > .top-state:not(:last-child) {
    margin-bottom: 10px;
  }
}
.top-state {
  box-sizing: border-box;

  h2 {
    font-size: 16px;
  }
  > div {
    background: #fff;

    padding: 15px 20px;
    box-sizing: border-box;
  }
  > div:not(:last-child) {
    margin-bottom: 20px;
  }
  .wx-con {
    display: flex;
    align-items: center;
    line-height: 22px;
  }
  .wx-img {
    width: 80px;
    height: 80px;
    position: relative;
    margin: 24px 44px 24px 0;
  }
  .cancel-wx {
  }

  .table-footer {
    background: #fff;
    border-radius: 0 0 3px 3px;

    display: flex;
    justify-content: space-between;

    padding: 0px 10px 10px 10px;

    .list-info {
      color: #767e89;

      font-size: 13px;
      line-height: 32px;

      margin: 0;

      .iconfont {
        position: relative;
        top: 1px;
      }
    }

    .el-pagination__jump {
      margin-left: 0;
    }
  }

  .set-arr-item {
    display: flex;
    border-bottom: 10px;
    .set-arr-item-left {
      min-width: 390px;
      .small-form {
        font-size: 12px;
        margin-top: 10px;
        input {
          width: 40px;
          height: 20px;
          font-size: 12px;
          padding: 1px;
          text-align: center;
        }
      }
      span {
        font-size: 14px;
        font-weight: 600;
        // cursor: pointer;
      }

      p:last-child {
        font-size: 12px;
        margin-top: 10px;
      }
    }

    .set-arr-item-right {
      display: flex;
      width: 400px;
      min-width: 400px;
      align-items: center;
      p:first-child {
        font-size: 14px;
      }
    }
  }
  .set-arr-box .set-arr-item:not(:last-child) {
    margin-bottom: 10px;
  }
  .productRegister {
    padding: 0 0 20px 0;
    h2 {
      height: 49px;
      line-height: 49px;
      border-bottom: solid 1px #e8e8e8;
      padding:0 16px;
      margin-bottom: 16px;
      span {
        cursor: pointer;
        font-weight: normal;
        margin-left: 24px;
        cursor: pointer;
        color: $color-primary-light-6;
      }
    }
    .flex{
      padding:0 16px;
    }
    .el-upload-listImg{
      width: 104px;
      height: 104px;
      border-radius: 4px;
      display: inline-block;
      margin-right: 10px;
    }
    .uploadPictures{
      border-radius: 4px;
      margin: 12px 16px 0;
      display: flex;
      .uploadIcon{
        font-size: 32px;
        color: #595959;
        margin: 15px auto 0;
      }
      .uploadText{
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #595959;
        line-height: 22px;
      }
    }
    .uploadTips {
      margin-left:16px;
      .tips{
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #595959;
        line-height: 20px;
      }
    }
    
  }
}

.upfile-title {
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #262626;
  line-height: 14px;
}

.el-switch__label {
  color: #b8bebc;
}

.el-image-viewer__img {
  width: auto;
  height: auto;
}
</style>

<style lang="scss" scoped>
  ::v-deep .el-upload--picture-card {
    margin-bottom: 17px;
  }
</style>